(function() {

 consts={
      shadowBoxZindex:65535,
      modelDialogBoxZindex:65535,
      modelDialogBoxId:1,
      styleIndex:0,
      wrapIndex:1,
      load:$("<div id='loading'></div>")
  }

	$.fn.shadowBox = function(){
		
		function shadowBoxHtml(){
			return ["<div id='shadowDiv'></div>"].join("");
		}
		
		var self = this;
		
		$.extend(self,{
				_init : function(){
					if($("#shadowDiv").size()==0){
						//初始化视图
						self._initView();
					}else{
						self.box=$("#shadowDiv");
            self.increaseZindex();
					}
				},
				_initView : function(){
					$(shadowBoxHtml()).prependTo($("body"));
					self.box=$("#shadowDiv");
          self.increaseZindex();
					self.setPos();
				},
				setPos:function(){
					if($("body").height()>$(document).height()){
			            self.box.each(function(i,o){
						 	$(o).css("width",($("body").width()+"px"));
							$(o).css("height",($("body").height()+"px"));
					 		});
					}else{
						self.box.each(function(i,o){
						 	$(o).css("width",($("body").width()+"px"));
							$(o).css("height",($(document).height()+"px"));
					 		});
					}
				},
				show:function(){
		      self.box.css("display","block");
				},
				hide:function(){
					self.box.css("display","none");
				},
        increaseZindex:function(){
          self.box.css("z-index",++consts.shadowBoxZindex);
        },
        decreaseZindex:function(){
          self.box.css("z-index",--consts.shadowBoxZindex);
        }
			});
		self._init();
	};
			    
	var modelDialogBox = function(opti){
		
		function emptyModelEmptyDialogBoxHtml(modelDialogBoxId){
			return ["<div data-tip='"+modelDialogBoxId+"' class='modelDialogBox' id='modelDialogBox_"+modelDialogBoxId+"'>",
			        	"<div class='t'><i></i><span></span></div>",
			        	"<div class='c'></div>",
                "<input type='hidden' value='' id='wrapID' />",
					"</div>"].join("");
		}
		var self = this;

		self.opti=$.extend({
        parent:$("body"),
				title:"",
				width:400,
				height:300,
				type:"msg",//"iframe","msg","ajax","selector","sel_clone"
				content:"msg",
				data:"",// data 只用于 ajax
				close:"x",
				style:"/sites/all/themes/globalzt/css/modelDialogBox.css"
		},opti||{});
		
		$.extend(self,{
				_init : function(){
						if(consts.styleIndex == 0){  
							self._loadStyle(self.opti.style);
							consts.styleIndex++;
						}
						//初始化视图
						self._initView();
						//初始化事件
				 		self._initEvent();       
						self.contentHeight = (self.opti.height-parseInt(self.box.find(".t").css("height")))+"px";
					  self._initAtti();
				},
				_loadStyle :function(href) {
					var link = document.createElement('link');
					link.href= href ;
					link.type='text/css';
					link.rel='stylesheet';
					document.body.appendChild(link);
				},
				_initView : function(){
					self.sb=new $.fn.shadowBox();
					self.sb.show();
					$(emptyModelEmptyDialogBoxHtml(consts.modelDialogBoxId)).appendTo(self.opti.parent);
					self.box = $("#modelDialogBox_"+consts.modelDialogBoxId);
          self.increaseZindex();
          consts.modelDialogBoxId++;					
				},
				_initAtti:function(){
          self.setContent();
					self.box.css("width",self.opti.width+"px").css("height",self.opti.height+"px");
          // 得到浏览器滚动条垂直偏移量
          var scrollTopHeight = $(document).scrollTop();
					// 得到浏览器滚动条左偏移量
          var scrollLeftHeight = $(document).scrollLeft();
          // 得到浏览器的高度
          var windowHeight = $(window).height();
          // 得到浏览器的宽度
          var windowWidth = $(window).width();
          self.box.css("left",((windowWidth/2-self.opti.width/2+scrollLeftHeight)+"px"));
					self.box.css("top",((windowHeight/2-self.opti.height/2+scrollTopHeight)+"px"));

					self.box.find(".t i").text(self.opti.title);
          self.box.find(".t span").text(self.opti.close);
          self.box.find(".c").css("height",(self.opti.height-self.box.find(".t").height())+"px");
					self.show();
				},
				_initEvent : function(){
					self.box.find(".t span").bind('click',function(){
						self.hide();
					});
				},
				show:function(){
					self.box.fadeIn("slow");
					$(document).bind("keyup",function(event){
						if(27==event.which||27==event.keyCode){
							self.hide();
							$(document).unbind();
						}
					});
        },
				hide:function(){
          self.box.fadeOut("slow");

          var boxContent = self.box.find(".c").html(),
              wrapID = $("#wrapID",self.box).val(),
              wrap = window.top.$("#wrap_"+wrapID);
          if(wrap.length == 1){
             wrap.replaceWith(boxContent);
          }

          self.box.remove();
          // 取得当前弹出框的标志ID,因为再弹出框弹出后，系统默认将标志ID加了1，所以这里要减回来！
          var box_id = consts.modelDialogBoxId - 1;
          if(box_id==1){
					  self.sb.hide();
          }else{
            self.sb.decreaseZindex();
            self.decreaseZindex();
          }
          consts.modelDialogBoxId--;
					if(self.opti.onClosed != ""){
						this.opti.onClosed();
					}
				},
        increaseZindex:function(){
          self.box.css("z-index",++consts.modelDialogBoxZindex);
        },
        decreaseZindex:function(){
          self.box.css("z-index",--consts.modelDialogBoxZindex);
        },
        close:function(){
          self.box.find(".close").click(function(){
             self.hide();
          });
        },
        setContent:function(){
          switch(self.opti.type){
            case "msg":
                self.box.find(".c").html(self.opti.content);
                break;
            case "ajax":
                var cdata = "",
                    url = self.opti.content,
                    data = self.opti.data;// 通过PHP的json_encode()方法 得到的是一个"{"":"","":""}"字符串
                if(data.length){
                  // 字符串处理
                  data = data.substr(1,data.length-2);// 去掉首尾的{}
                  var data_arr = data.split(',');
                  for(var i = 0;i<data_arr.length;i++){
                     var item = data_arr[i],
                         item_arr = item.split(':');
                         cdata += item_arr[0].substr(1,item_arr[0].length-2) + "=" + item_arr[1].substr(1,item_arr[1].length-2) + "&"; 
                  }
                  cdata = cdata.substr(0,cdata.length-1);// 去掉字符串最后多添加的一个&
                }
                $.ajax({
                   type:"post",
                   url:url,
                   dataType:"json",
                   data:cdata,
                   beforeSend:function(){
                      self.box.find(".c").append(consts.load);
                      self.box.find(".c").find("#loading").css("width",self.opti.width+"px").css("height",self.contentHeight);
                   },
                   success: function(response) {
                      if(response.status === 1){
                        self.box.find(".c").html(response.data);
                        self.close();
                      }
                   }
                });
                break; 
            case "iframe":
                var src = self.opti.content;
                self.box.find(".c").append(consts.load);
                self.box.find(".c").find("loading").css("width",self.opti.width+"px").css("height",self.contentHeight);
                var iframe = document.createElement("iframe");
                iframe.src = src;
                iframe.width = '100%';
                iframe.height = self.contentHeight;
                iframe.scrolling = 'no';
                iframe.setAttribute("frameborder","0");
                self.box.find(".c").html("");
                self.box.find(".c").append(iframe); 
                self.close();
                break;
            case "selector":
                // 直接取页面上的内容并弹出 ， 内容弹出后，在关闭弹出框后应该将内容放回原来的位置 
                var c = $(self.opti.content),
								    //c2 = c1.clone(true),
                    wrap = "<div id='wrap_"+consts.wrapIndex+"'></div>";
                // 设置内容标志包裹div
                c.replaceWith(wrap);
                $("#wrapID",self.box).val(consts.wrapIndex);     
                consts.wrapIndex++;
                self.box.find(".c").append(c);
                self.close();
								/*if(self.onComplete != ""){
									self.opti.onComplete.call();
								}
                */
                break;
            case "sel_clone":      
                var c = $(self.opti.content).clone(true);
                self.box.find(".c").append(c);
                self.close();
                break;
          }
        }
			});
		self._init();
	};
	
	$.modelDialogBox=function(opti){
		return new modelDialogBox(opti);
	}
})();